//api文件夹用于存放对后台请求的代码
import axios from 'axios'//导入axios
import {ElMessage} from 'element-plus';
import router from '@/router';
import {useTokenStore} from '@/stores/token.js';
import {useUserStore} from "@/stores/user.js";
import rsaUtil from "@/utils/rsa.ts";
import aesUtil from "@/utils/aes.ts";
//使用store
//返回自定义配置新建一个axios实例
const service = axios.create({
    baseURL: import.meta.env.VITE_SERVER_ADDR
});

//Axios的请求拦截器
service.interceptors.request.use(req => {
    //携带token，只要有token就携带
    const tokenStore = useTokenStore();
    //如果不是登入请求就要在请求头中添加token
    if (tokenStore.tokenStr) {
        req.headers.token = tokenStore.tokenStr;
    }
    return req;
}, error => {
    //对请求错误做写什么
    //return Promise.reject(error);
})

//Axios的响应拦截器
service.interceptors.response.use(resp => {
    //刷新token
    const token = resp.headers.token;
    if (token) {
        const tokenStore = useTokenStore();
        tokenStore.update(token);
    }
    if (resp.data.data && resp.data.data.aesKey) {
        const decryptedAesKey = rsaUtil.decrypt(resp.data.data.aesKey, "MIICXAIBAAKBgQCSLVRNSZohtMIVwegr27CwHVeNfBh58OWG0Cjsn/cxjnxQqRKAy6EOuw5WHAy80tawUvUwRyiHVxKFo7VGLsJe1O+iABcP9R33lIACTvlJX4zNWXb6XiE2Cghk+U1Ya3yQeHTgKMzNXffqjI8Jh+HBMgw5taR3oiWZ2VZei2hkwwIDAQABAoGBAJGfuPE6FuPnWMcmIu62cQIyaQuZiiTJGVBBxdNd1Xw4L56HoNhQhEXRkgm07fear6h/LKaI7VZPJzOdkLS3Vohyb+TpssW5sGgfm2rtmhq2HE8WJCV1zmQmGJaKNGlL8KpbWt9XBmga5HRx0ml4I7f4UZcAKqkqcTrbw2orGswxAkEA0CWwi0m5KjFGAIcQxRuNBkqi165bgd7M1c3pqWYloGyi9fbgiMbT3d7BbA1r+Gm0lFgOwBR/LToaOZBR72PnuQJBALPIcajn7QVo/bFlywawIwofyyVTLfJc4ssORQS5tmeyF60n7uP6y5V/P0mcayFCht2eRoRlHsfLEAcbehokNlsCQClwB2iDYciDjLMYMH99D6M8ApU7kd4V8+Nwnd7qhf0dA4hCAMtaAd2+tfUD6wXGTXvm1/DnY7YmRghFsfodgokCQH4xqqZ29YagpcLJwvMU2+OVYZD3i/7deEwz3fptKT4sYjYnG6ZnOlPbl97hrskP237gRHtWR37SaJO0k8aZuJUCQFR6NsBDdZDqtblGIk7JUdPixwVE8HB/PT5F5YDBXdjljlEA59sjCAvKbsyT90wPhQ5I4LGPAvFXonhcDHAZfdI=");
        resp.data = aesUtil.decrypt(resp.data.data.data, decryptedAesKey);
    }
    return resp.data;
}, error => {
    //403--令牌
    if (error.status === 403) {
        ElMessage.error({
            message: ',请重新登入',
            duration: 1200,
            onClose: () => {//提示信息消失时的回调
                //将store中的token设置为处置null
                const tokenStore = useTokenStore();
                const userStore = useUserStore();
                tokenStore.$reset()
                let currentPath = router.currentRoute.value.path;
                if (currentPath.startsWith("/admin")) {
                    router.push('/admin/login');//跳转到管理员登入页
                } else {
                    router.push('/user/login');//跳转到用户登入页
                }
            }
        });
    }
})
export default service;//新建实例导出